package com.example.zhinongbao.Fragment;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.zhinongbao.R;
import com.example.zhinongbao.provider.ZhinongbaoContract;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class PostFragment extends Fragment {

    private EditText etContent;
    private RadioGroup rgPostType;
    private ImageView ivSelectedImage;
    private int selectedPostType = ZhinongbaoContract.FriendCircle.TYPE_FOLLOWING;
    private Uri selectedImageUri;

    // 图片选择启动器
    private final ActivityResultLauncher<Intent> imagePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == getActivity().RESULT_OK && result.getData() != null) {
                    selectedImageUri = result.getData().getData();
                    if (selectedImageUri != null) {
                        Log.d("PostFragment", "Selected image URI: " + selectedImageUri);
                        ivSelectedImage.setVisibility(View.VISIBLE);
                        Glide.with(this)
                                .load(selectedImageUri)
                                .into(ivSelectedImage);
                    }
                }
            });

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_post, container, false);

        // 初始化视图
        etContent = view.findViewById(R.id.etContent);
        rgPostType = view.findViewById(R.id.rgPostType);
        ivSelectedImage = view.findViewById(R.id.ivSelectedImage);

        // 设置发布类型选择监听
        rgPostType.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rbFollow) {
                selectedPostType = ZhinongbaoContract.FriendCircle.TYPE_FOLLOWING;
            } else if (checkedId == R.id.rbLatest) {
                selectedPostType = ZhinongbaoContract.FriendCircle.TYPE_LATEST;
            }
        });

        // 初始化返回按钮
        view.findViewById(R.id.btnBack).setOnClickListener(v -> requireActivity().onBackPressed());

        // 初始化发布按钮
        view.findViewById(R.id.btnPost).setOnClickListener(v -> postContent());

        // 初始化添加图片按钮
        view.findViewById(R.id.btnAddImage).setOnClickListener(v -> selectImage());

        return view;
    }

    private void selectImage() {
        try {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            imagePickerLauncher.launch(intent);
        } catch (Exception e) {
            Log.e("PostFragment", "Image selection failed", e);
            Toast.makeText(getContext(), "无法打开相册", Toast.LENGTH_SHORT).show();
        }
    }

    private void postContent() {
        String content = etContent.getText().toString().trim();

        if (content.isEmpty() && selectedImageUri == null) {
            Toast.makeText(getContext(), "请输入内容或添加图片", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建要插入的内容
        ContentValues values = new ContentValues();
        values.put(ZhinongbaoContract.FriendCircle.COLUMN_CONTENT, content);
        values.put(ZhinongbaoContract.FriendCircle.COLUMN_TYPE, selectedPostType);
        values.put(ZhinongbaoContract.FriendCircle.COLUMN_USER_ID, getCurrentUserId());
        values.put(ZhinongbaoContract.FriendCircle.COLUMN_USER_NAME, getCurrentUserName());
        values.put(ZhinongbaoContract.FriendCircle.COLUMN_CREATE_TIME, System.currentTimeMillis());

        // 处理图片数据
        if (selectedImageUri != null) {
            try {
                // 方法1：使用输入流直接读取（推荐）
                InputStream inputStream = requireContext().getContentResolver().openInputStream(selectedImageUri);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, length);
                }

                values.put(ZhinongbaoContract.FriendCircle.COLUMN_IMAGE_DATA, outputStream.toByteArray());

                inputStream.close();
                outputStream.close();

                // 方法2：使用Bitmap（备用方案）
                /*
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(
                        requireContext().getContentResolver(), selectedImageUri);
                // 压缩图片避免OOM
                bitmap = compressBitmap(bitmap, 1024); // 最大边长为1024px
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
                values.put(ZhinongbaoContract.FriendCircle.COLUMN_IMAGE_DATA, stream.toByteArray());
                stream.close();
                */

            } catch (IOException e) {
                Log.e("PostFragment", "Image processing failed", e);
                Toast.makeText(getContext(), "图片处理失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        // 插入数据
        try {
            Uri uri = requireContext().getContentResolver().insert(
                    ZhinongbaoContract.FriendCircle.CONTENT_URI,
                    values
            );

            if (uri != null) {
                Log.d("PostFragment", "Post created at: " + uri.toString());
                Toast.makeText(getContext(), "发布成功", Toast.LENGTH_SHORT).show();
                requireActivity().onBackPressed();
            } else {
                Toast.makeText(getContext(), "发布失败：返回URI为空", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e("PostFragment", "Post creation failed", e);
            Toast.makeText(getContext(), "发布失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // 图片压缩方法（备用）
    private Bitmap compressBitmap(Bitmap source, int maxSize) {
        int width = source.getWidth();
        int height = source.getHeight();

        float ratio = (float) width / (float) height;
        if (width > height) {
            width = maxSize;
            height = (int) (width / ratio);
        } else {
            height = maxSize;
            width = (int) (height * ratio);
        }

        return Bitmap.createScaledBitmap(source, width, height, true);
    }

    private String getCurrentUserId() {
        // TODO: 替换为实际获取用户ID的方法
        return "user123";
    }

    private String getCurrentUserName() {
        // TODO: 替换为实际获取用户名的方法
        return "当前用户";
    }
}